<template>
  <div class="products">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">产品管理</span>
      </div>
      <!-- 查询表单 -->
      <el-row>
        <el-col :span="24">
          <el-form inline class="query-form">
            <el-form-item label="商品编码">
              <el-input
                v-model="query.productId"
                placeholder="请输入商品编码"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input
                v-model="query.productName"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="商店编码">
              <el-input
                v-model="query.storeId"
                placeholder="请输入商店编码"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品类别">
              <el-select v-model="query.categoryId" placeholder="请选择类别">
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24">
          <el-button type="success" @click="handleAdd" class="add-button"
            >新增商品</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格展示 -->
      <el-row>
        <el-col :span="24">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            class="product-table"
          >
            <el-table-column
              prop="productId"
              label="商品编码"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="productName"
              label="商品名称"
              align="center"
            ></el-table-column>
            <el-table-column label="商品图片" align="center">
              <template slot-scope="scope">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.productImage"
                  fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column
              prop="price"
              label="商品售价"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="stock"
              label="商品数量"
              align="center"
            ></el-table-column>
            <el-table-column label="商品类别" prop="categoryId" align="center">
              <template slot-scope="scop">
                {{ getCategoryKey(scop.row.categoryId) }}
              </template>
            </el-table-column>
            <el-table-column label="商店名称" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="showStoreDetails(scope.row)">{{
                  scope.row.storeName
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              prop="companyName"
              label="组织名称"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="24">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="productForm"
        :model="productForm"
        :rules="rules"
        label-width="100px"
        class="edit-form"
      >
        <el-form-item label="商品编码">
          <el-input
            v-model="productForm.productId"
            placeholder="请输入商品编码"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="productForm.productName"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品图片" class="left-item">
          <el-upload
            class="avatar-uploader"
            action="about:blank"
            :auto-upload="false"
            :on-change="handleImageSelect"
            :show-file-list="false"
          >
            <img
              v-if="productForm.productImage"
              :src="productForm.productImage"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品售价" class="left-item" prop="price">
          <el-input-number
            v-model="productForm.price"
            :min="0"
            placeholder="请输入商品售价"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品数量" class="left-item" prop="stock">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            placeholder="请输入商品数量"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input
            v-model="productForm.description"
            placeholder="请输入商品描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="商店编码" prop="storeId">
          <el-select
            v-model="productForm.storeId"
            placeholder="请选择商店"
            @change="selectStore"
            style="float: left"
          >
            <el-option
              v-for="store in stores"
              :key="store.storeId"
              :label="store.storeName"
              :value="store.storeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类别" prop="categoryId">
          <el-select
            v-model="productForm.categoryId"
            style="float: left"
            placeholder="请选择类别"
          >
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.key"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织编码" prop="organizationId">
          <el-select
            v-model="productForm.organizationId"
            placeholder="请选择组织"
            @change="selectOrganization"
            style="float: left"
          >
            <el-option
              v-for="org in organizations"
              :key="org.organizationId"
              :label="org.companyName"
              :value="org.organizationId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </span>
    </el-dialog>

    <!-- 商店详情对话框 -->
    <el-dialog title="商店详情" :visible.sync="storeDetailsVisible" width="30%">
      <p><strong>商店编码：</strong>{{ selectedStore.storeId }}</p>
      <p><strong>商店名称：</strong>{{ selectedStore.storeName }}</p>
      <p><strong>组织编码：</strong>{{ selectedStore.organizationId }}</p>
      <p><strong>组织名称：</strong>{{ selectedStore.companyName }}</p>
    </el-dialog>
  </div>
</template>

<script>
import { getAllOrganizations } from "@/api/organizationsApi";
import {
  deleteProduct,
  productCreate,
  productsPageQuery,
  updateProduct,
  updateProductImageUrl,
  uploadProductImage,
} from "@/api/productsApi";
import { getAllStore } from "@/api/storeApi";

export default {
  name: "AdminProducts",
  data() {
    return {
      query: {
        productId: "",
        productName: "",
        storeId: "",
        categoryId: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      dialogTitle: "新增商品",
      productForm: {
        productId: "",
        productName: "",
        productImage: "",
        imageFile: null,
        price: 0,
        stock: 0,
        description: "",
        storeId: "",
        organizationId: "",
        categoryId: "",
      },
      currentProduct: null,
      stores: [],
      organizations: [],
      storeDetailsVisible: false,
      selectedStore: {},
      selectedCategory: null,
      categories: [
        { key: "数码电器", value: 1 },
        { key: "家具厨具", value: 2 },
        { key: "服装箱包", value: 3 },
        { key: "美妆清洁", value: 4 },
        { key: "食品生鲜", value: 5 },
        { key: "图书文娱", value: 6 },
      ],
      rules: {
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请输入商品售价", trigger: "blur" },
          { type: "number", message: "商品售价必须为数字", trigger: "blur" },
        ],
        stock: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
          { type: "number", message: "商品数量必须为数字", trigger: "blur" },
        ],
        storeId: [{ required: true, message: "请选择商店", trigger: "change" }],
        organizationId: [
          { required: true, message: "请选择组织", trigger: "change" },
        ],
        categoryId: [
          { required: true, message: "请选择商品类别", trigger: "change" },
        ],
      },
    };
  },

  methods: {
    getCategoryKey(value) {
      const categorie = this.categories.find((r) => r.value === value);
      return categorie ? categorie.key : "其他类别";
    },
    fetchData() {
      productsPageQuery({
          query: this.query,
          pageRequestDto: {
            page: this.currentPage,
            size: this.pageSize,
          },
        })
        .then((response) => {
          console.log("响应数据：",response.data.records)
          this.tableData = response.data.records || [];
          console.log("table数据：",this.tableData)

          this.total = response.data.total || 0;
        })
        .catch((error) => {
          this.$message.error("加载商品数据失败");
          console.error("Error fetching product data:", error);
        });
    },
    resetQuery() {
      this.query = {
        productId: "",
        productName: "",
        storeId: "",
        categoryId: "",
      };
      this.fetchData();
    },
    handleAdd() {
      this.dialogTitle = "新增商品";
      this.productForm = {
        productId: "",
        productName: "",
        productImage: "",
        imageFile: null,
        price: 0,
        stock: 0,
        description: "",
        storeId: "",
        organizationId: "",
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑商品";
      this.productForm = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm(`确定要删除商品 ${row.productId} 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteProduct(row.productId)
            .then(() => {
              this.$message.success("删除成功");
              this.fetchData();
            })
            .catch((error) => {
              this.$message.error("删除失败");
              console.error("Error deleting product:", error);
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    saveProduct() {
      this.$refs.productForm
        .validate()
        .then(() =>
          this.dialogTitle === "新增商品"
            ? productCreate(this.productForm)
            : updateProduct(this.productForm.productId, this.productForm)
        )
        .then((res) => {
          const productId = res.data?.productId || this.productForm.productId;
          return this.productForm.imageFile
            ? uploadProductImage(productId, this.productForm.imageFile).then(
                (uploadRes) =>
                  updateProductImageUrl(productId, uploadRes.data.fileUrl)
              )
            : Promise.resolve();
        })
        .then(() => {
          this.$message.success("商品保存成功");
          this.dialogVisible = false;
          this.fetchData();
        })
        .catch((error) => {
          this.$message.error(
            "保存商品失败：" + (error.response?.data?.message || error.message)
          );
          console.error("Error saving product:", error);
        });
    },
    handleImageSelect(file) {
      if (file.raw instanceof File) {
        this.productForm.imageFile = file.raw;
        console.log("Selected file:", this.productForm.imageFile);
        this.productForm.productImage = URL.createObjectURL(file.raw);
      } else {
        this.$message.error("上传的文件无效，请选择正确的图片文件！");
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    fetchStores() {
      getAllStore()
        .then((res) => {
          this.stores = res.data || [];
        })
        .catch((error) => {
          this.$message.error("加载商店数据失败");
          console.error("Error fetching stores:", error);
        });
    },
    fetchOrganizations() {
      getAllOrganizations()
        .then((res) => {
          this.organizations = res.data || [];
        })
        .catch((error) => {
          this.$message.error("加载组织数据失败");
          console.error("Error fetching organizations:", error);
        });
    },
    selectStore(storeId) {
      const selectedStore = this.stores.find(
        (store) => store.storeId === storeId
      );
      if (selectedStore) {
        this.productForm.storeName = selectedStore.storeName;
      }
    },
    selectOrganization(orgId) {
      const selectedOrg = this.organizations.find(
        (org) => org.organizationId === orgId
      );
      if (selectedOrg) {
        this.productForm.companyName = selectedOrg.companyName;
      }
    },
    showStoreDetails(row) {
      this.selectedStore = {
        storeId: row.storeId,
        storeName: row.storeName,
        organizationId: row.organizationId,
        companyName: row.companyName,
      };
      this.storeDetailsVisible = true;
    },
  },
  mounted() {
    this.fetchData();
    this.fetchStores();
    this.fetchOrganizations();
  },
};
</script>

<style scoped>
.products {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.product-table {
  margin-top: 20px;
}

.add-button {
  float: left;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.avatar {
  width: 50px;
  height: 50px;
  display: block;
}

.left-item {
  text-align: left;
}
</style>